package com.cs410.collabwriting.junit.main;

import junit.framework.Assert;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;

import com.cs410.collabwriting.main.Prompt;
import com.cs410.collabwriting.main.Story;
import com.cs410.collabwriting.main.StoryManager;
import com.cs410.collabwriting.main.User;
import com.cs410.collabwriting.main.UserManager;
import com.cs410.collabwriting.tools.LogManager;
import com.cs410.collabwriting.test.DatabaseUtility;

public class StoryTest{

	@Rule
	public TestName m_testName = new TestName();
	
	private static Story s_story;
	private static Prompt s_prompt;
	private static User s_user;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		LogManager.logInfo("[JUnitTest] -- Starting JUnit Tests for Story" );
		DatabaseUtility.DeleteAllTables();		
		Thread.sleep(1000);		
		DatabaseUtility.CreateAllTables();		
		Thread.sleep(1000);
		DatabaseUtility.CreateAllTestingData();
		Thread.sleep(10000);
		
		s_prompt = new Prompt(1);
        s_user = UserManager.getInstance().addUser("test", "password", "test@gmail.com");				
		s_story = StoryManager.getInstance().createStory("cary", s_user.getUserID(), s_prompt);
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		LogManager.logInfo("[JUnitTest] -- Finished JUnit Tests for Story" );
	}

	@Before
	public void setUp() throws Exception {
		LogManager.logInfo("[JUnitTest] -- Starting Test : " + m_testName.getMethodName() );
	}

	@After
	public void tearDown() throws Exception {
		LogManager.logInfo("[JUnitTest] -- Finished Test : " + m_testName.getMethodName() );
	}

	@Test
	public void getStoryIDTest() {
		int storyID = s_story.getStoryID();
		Assert.assertEquals(storyID, s_story.getStoryID());
	}
	
	@Test
	public void incrementViewCountTest() {
	    int count = s_story.getViewCount();
	    Assert.assertTrue(s_story.incrementViewCount());
	    
	    try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
	    
	    Assert.assertEquals(count + 1, s_story.getViewCount());
	}
	
	@Test
	public void upvoteStoryTest() {
	    int vote = s_story.getVoteCount();
	    Assert.assertTrue(s_story.upvoteStory(s_user.getUserID()));
	    
	    try {
	        Thread.sleep(1000);
	    } catch (InterruptedException e) {}
	    
	    Assert.assertEquals(vote + 1, s_story.getVoteCount());
	}
	
	@Test
	public void commentTest() {
	    int comments = s_story.getAllComments().size();
	    Assert.assertTrue(s_story.comment(s_user.getUserID(), "testcomment"));

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
        
        Assert.assertEquals(comments + 1, s_story.getAllComments().size());
	}
}
